package com.kkd.kkdapp.activity;

import java.text.DecimalFormat;

import org.json.JSONException;
import org.json.JSONObject;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.http.entity.PaymentBill;
import com.kkd.kkdapp.http.entity.PaymentData;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.utils.AuthenticationUtils;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class OverdueRepaymentActivity extends BaseActivity implements
		OnClickListener {

	private final int UNPAYBILL_CODE_ZERO = 1; // 按期还款详情 code=0
	private final int UNPAYBILL_CODE_ELSE = 2; // 按期还款详情 code=其它
	private final int ACCOUNTINFO_CODE_ZERO = 3; // 账户余额code=0
	private final int ACCOUNTINFO_CODE_ELSE = 4; // 账户余额code=其它
	private final int REPAYBILL_CODE_ZERO = 5; // 账户余额code=其它
	private final int REPAYBILL_CODE_ELSE = 6; // 立即还款code = 其它
	private RelativeLayout add_title_img;
	private TextView periods_tv; // 期数
	private TextView date_tv; // 　还款日期
	private TextView repayment_tv; // 　还款金额
	private TextView payment_tv; // 已还款金额
	private TextView deadline_tv; // 本金
	private TextView interest_tv; // 利率
	private TextView administrativefee_tv; // 管理费
	private Button Immediaterepayment_button; // 立即还款
	private TextView balance_tv; // 账户余额
	private String bid_id = "";
	private String bill_id = "";
	private boolean buttonflag = false; // 　控制还款按钮是否可以点击
	private boolean repayflag = false; // 是否是还款按钮调用账户余额
	private boolean balanceflag = false; // 是否余额不足，跳转充值还是立即还款
	private int bill_num;
	private String shouldPayDate;
	private String unPayMoney = "";
	private String havePayMoney;
	private String pcp;
	private String itt;
	private long serviceCharge;
	private String sc;
	private String buill_id;
	private Double balance;
	private String mBalance;
	private int mCode;
	private DecimalFormat df = new DecimalFormat("###,##0.00");
	private DecimalFormat df1 = new DecimalFormat("0.00");
	private Dialog toLoadDialog;
	private TextView overddate; // 逾期期限
	private TextView overdinterest; // 　逾期罚息
	private TextView overdmanage; // 逾期管理费
	private long overDay; // 逾期天数
	private long overheadCHarges; // 逾期管理费
	private long penaltyInteret; // 逾期罚息

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {

			String desc;
			Intent intent;
			switch (msg.what) {
			case UNPAYBILL_CODE_ZERO:
				periods_tv.setText("第" + bill_num + "期");
				date_tv.setText("还款日：" + shouldPayDate);
				repayment_tv.setText(unPayMoney);
				payment_tv.setText("已还金额（元） " + havePayMoney);
				deadline_tv.setText(pcp + "元");
				interest_tv.setText(itt + "元");
				overddate.setText(overDay + "天");
				overdinterest.setText(df.format(penaltyInteret * 0.01) + "元");
				overdmanage.setText(df.format(overheadCHarges * 0.01) + "元");
				if (serviceCharge == 0) {
					administrativefee_tv.setText("0.00" + "元");
				} else {
					administrativefee_tv.setText(sc + "元");
				}
				showToLoadDialog("正在获取账单信息，请稍等...");
				getAccountInfo();
				break;
			case UNPAYBILL_CODE_ELSE:
				desc = (String) msg.obj;
				showToast(desc);
				break;
			case ACCOUNTINFO_CODE_ZERO:
				if (balance == 0) {
					balance_tv.setText("0.00元");
				} else {
					balance_tv.setText(df.format(balance) + "元");
				}
				if (balance < Double
						.parseDouble(unPayMoney.replaceAll(",", ""))) {
					Immediaterepayment_button.setText("余额不足，请先充值");
					buttonflag = true;
					closeToLoadDialog();
					balanceflag = true;
				} else {
					Immediaterepayment_button.setText("还款");
					buttonflag = true;
					if (repayflag) {
						if (buill_id != null) {
							questRepayBill();
						}
						repayflag = false;
					} else {
						closeToLoadDialog();
					}
					balanceflag = false;
				}
				break;
			case ACCOUNTINFO_CODE_ELSE:
				desc = (String) msg.obj;
				showToast(desc);
				break;
			case REPAYBILL_CODE_ZERO:
				closeToLoadDialog();
				desc = (String) msg.obj;
				intent = new Intent(OverdueRepaymentActivity.this,
						RepaymentResultActivity.class);
				intent.putExtra("desc", desc);
				intent.putExtra("bill_num", bill_num);
				intent.putExtra("unPayMoney", unPayMoney);
				intent.putExtra("mBalance", mBalance);
				intent.putExtra("mCode", mCode);
				startActivity(intent);
				finish();
				break;
			case REPAYBILL_CODE_ELSE:
				closeToLoadDialog();
				desc = (String) msg.obj;
				showToast(desc);
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_overdue_repayment);
		initView();
		setListener();
		getMessage();
	}

	public void initView() {
		add_title_img = (RelativeLayout) this.findViewById(R.id.add_title_img);
		periods_tv = (TextView) this.findViewById(R.id.periods_tv);
		date_tv = (TextView) this.findViewById(R.id.date_tv);
		repayment_tv = (TextView) this.findViewById(R.id.repayment_tv);
		payment_tv = (TextView) this.findViewById(R.id.payment_tv);
		deadline_tv = (TextView) this.findViewById(R.id.deadline_tv);
		interest_tv = (TextView) this.findViewById(R.id.interest_tv);
		administrativefee_tv = (TextView) this
				.findViewById(R.id.administrativefee_tv);
		Immediaterepayment_button = (Button) this
				.findViewById(R.id.Immediaterepayment_button);
		balance_tv = (TextView) this.findViewById(R.id.balance_tv);
		overddate = (TextView) this.findViewById(R.id.overddate);
		overdinterest = (TextView) this.findViewById(R.id.overdinterest);
		overdmanage = (TextView) this.findViewById(R.id.overdmanage);
	}

	public void setListener() {
		add_title_img.setOnClickListener(this);
		Immediaterepayment_button.setOnClickListener(this);
	}

	public void getMessage() {
		Intent intent = this.getIntent();
		String mbid_id = intent.getStringExtra("bidId");
		if (TextUtils.isEmpty(mbid_id)) {
			bid_id = "";
		} else {
			bid_id = mbid_id;
		}
		String mbill_id = intent.getStringExtra("bill_id");
		if (TextUtils.isEmpty(mbill_id)) {
			bill_id = "";
		} else {
			bill_id = mbill_id;
		}
		questUnpayBill();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.add_title_img: // 返回
			finish();
			break;
		case R.id.Immediaterepayment_button: // 立即还款
			if (buttonflag) {
				if (balanceflag) { // 余额不足去充值
					AuthenticationUtils.getAuthenticationResult(this, 3,
							RechargeActivity.class);
				} else { // 　余额充足去还款

					LogUtil.e("魔术", "好神奇啊");
					showToLoadDialog("正在还款，请不要关闭页面");
					getAccountInfo();
					repayflag = true;
				}
			}
			break;
		}
	}

	/**
	 * 按期还款详情
	 */
	public void questUnpayBill() {
		KkdHttpMagager.getInstance().getUnpayBill(bid_id, bill_id,
				PaymentData.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						PaymentData data = (PaymentData) responseBody;
						if (data != null) {
							PaymentBill bill = data.getBill();
							bill_num = bill.getBill_num();
							shouldPayDate = bill.getShouldPayDate();
							unPayMoney = bill.getUnPayMoney();
							havePayMoney = bill.getHavePayMoney();
							long principal = bill.getPrincipal();
							pcp = df.format(principal * 0.01);
							int interest = bill.getInterest();
							itt = df1.format(interest * 0.01);
							serviceCharge = bill.getServiceCharge();
							sc = df.format(serviceCharge * 0.01);
							buill_id = bill.getBill_id();
							LogUtil.e("buill_id", buill_id);
							overDay = bill.getOverDay();
							overheadCHarges = bill.getOverheadCharges();
							penaltyInteret = bill.getPenaltyInteret();
							mHandler.sendEmptyMessage(UNPAYBILL_CODE_ZERO);
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = new Message();
						msg.what = UNPAYBILL_CODE_ELSE;
						msg.obj = desc;
						mHandler.sendMessage(msg);
					}
				});
	}

	/**
	 * 
	 * 查询账户余额
	 */
	public void getAccountInfo() {

		KkdHttpMagager.getInstance().getAccountInfoManager(String.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						try {
							String responseString = responseBody.toString();
							JSONObject data = new JSONObject(responseString);
							balance = data.getDouble("balance");
							mHandler.sendEmptyMessage(ACCOUNTINFO_CODE_ZERO);
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = new Message();
						msg.obj = desc;
						msg.what = ACCOUNTINFO_CODE_ELSE;
					}
				});
	}

	/***
	 * 立即还款接口
	 */
	public void questRepayBill() {
		showToLoadDialog("正在还款，请不要关闭页面");
		KkdHttpMagager.getInstance().getRepayBill(buill_id, 
				String.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						try {
							String responseString = responseBody.toString();
							JSONObject data = new JSONObject(responseString);
							mBalance = data.getString("balance");
							mCode = data.getInt("code");
							Message msg = new Message();
							msg.what = REPAYBILL_CODE_ZERO;
							msg.obj = data.getString("result");
							mHandler.sendMessage(msg);
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						LogUtil.e("statusCode", "" + statusCode);
						Message msg = new Message();
						msg.what = REPAYBILL_CODE_ELSE;
						msg.obj = desc;
						mHandler.sendMessage(msg);
					}
				});

	}

	public void showToLoadDialog(String content) {
		if (toLoadDialog != null) {
			toLoadDialog.cancel();
			toLoadDialog = null;
		}
		toLoadDialog = DialogUtils.toLoadDialog(this, content);
		toLoadDialog.show();
	}

	public void closeToLoadDialog() {
		if (toLoadDialog != null) {
			toLoadDialog.dismiss();
			toLoadDialog.cancel();
			toLoadDialog = null;
		}
	}
}
